﻿using System;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using com.yoozoo.gta.Extension.UGUI.ScreenOrientationEx;
using UnityEditor.SceneManagement;

namespace com.yoozoo.gta.Extension.UGUI.Editor
{

    [InitializeOnLoad] 
    public class HierarchyItemChangeDetector
    {
        static Dictionary<int, Component[]> componentsByGameObjectId = new Dictionary<int, Component[]>();
        static bool inUIPrefabStage = false;
        private static bool inHandling;
        private const string UIRootPath = "Assets/ResourcesAssets/Prefabs/UI";
        private const string ResourceUIRootPath = "Assets/ResourcesAssets/Prefabs/UI";
        static HierarchyItemChangeDetector()
        {
            EditorApplication.hierarchyWindowItemOnGUI += HierarchyWindowItemOnGUI;
            
            
            
            EditorApplication.playModeStateChanged += (state) =>
            {
                if (state == PlayModeStateChange.ExitingEditMode)
                {
                    componentsByGameObjectId.Clear();
                }
            };
            PrefabStage.prefabStageOpened += PrefabStageOpened;
            PrefabStage.prefabStageClosing += PrefabStageClosing;
        }

        private static void PrefabStageClosing(PrefabStage obj)
        {
           
            componentsByGameObjectId.Clear();
            inUIPrefabStage = false;
        }

        private static void PrefabStageOpened(PrefabStage obj)
        {
            if (obj.assetPath.Contains(UIRootPath) || obj.assetPath.Contains(ResourceUIRootPath))
            {
                inUIPrefabStage = true;
            }
            inUIPrefabStage = false;
        }

        static void HierarchyWindowItemOnGUI(int instanceID, Rect selectionRect)
        {
            
            if(Application.isPlaying || !inUIPrefabStage)
            {
                return;
            }
            if(Selection.activeInstanceID != instanceID)
            {
                return;
            }
            
            if(ScreenOrientManager.GetInstance().InspectorAutoAddAdapter == false)
            {
                return;
            }
            if(ScreenOrientItem.CleanUpByHand)
            {
                ScreenOrientItem.CleanUpByHand = false;
                return;
            }
            try  
            {
               
                GameObject gameObject = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
                if (gameObject != null)
                {
                    Component[] newComponents = gameObject.GetComponents<Component>();
                    if (componentsByGameObjectId.TryGetValue(instanceID, out var oldComponents))
                    {
                        if (!AreComponentListsEqual(oldComponents, newComponents))
                        {
                            UnityEngine.Debug.Log("Components changed on GameObject: " + gameObject.name + " rect : " + selectionRect);
                            componentsByGameObjectId[instanceID] = newComponents; 
                            var screenOrientItem = gameObject.GetComponentInParent<ScreenOrientItem>();
                            ScreenOrientItem.AddNeedAdapterToGameObject(gameObject.transform, screenOrientItem);
                            ScreenOrientItem.RemoveUnNeedAdapterFormGameObject(gameObject.transform, screenOrientItem);
                        }
                    }
                    else
                    {
                        componentsByGameObjectId[instanceID] = newComponents;
                    }
                }
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogErrorFormat("HierarchyWindowItemOnGUI : "+e);
            }
        }

        static bool AreComponentListsEqual(Component[] list1, Component[] list2)
        {
            if (list1.Length != list2.Length)
            {
                return false;
            }

            for (int i = 0; i < list1.Length; i++)
            {
                if (list1[i] != list2[i])
                {
                    return false;
                }
            }

            return true;
        }
    }
}